from rest_framework import serializers
from .models import Order, OrderItem, Review
from restaurant.serializers import DishSerializer

class OrderItemSerializer(serializers.ModelSerializer):
    dish_details = DishSerializer(source='dish', read_only=True)
    
    class Meta:
        model = OrderItem
        fields = ['id', 'dish', 'dish_details', 'quantity', 'price']

class ReviewSerializer(serializers.ModelSerializer):
    class Meta:
        model = Review
        fields = ['id', 'order', 'rating', 'comment', 'created_at']
        read_only_fields = ['created_at']

class OrderSerializer(serializers.ModelSerializer):
    items = OrderItemSerializer(many=True, read_only=True)
    review = ReviewSerializer(read_only=True)
    total_amount = serializers.DecimalField(max_digits=10, decimal_places=2, read_only=True)
    
    class Meta:
        model = Order
        fields = ['id', 'user', 'restaurant', 'status', 'total_amount', 
                 'delivery_address', 'created_at', 'updated_at', 'items', 'review']
        read_only_fields = ['user', 'created_at', 'updated_at']
    
    def create(self, validated_data):
        items_data = self.context.get('items', [])
        if not items_data:
            raise serializers.ValidationError("订单必须包含至少一个商品")
        
        order = Order.objects.create(**validated_data)
        total_amount = 0
        
        for item_data in items_data:
            item = OrderItem.objects.create(
                order=order,
                dish_id=item_data['dish'],
                quantity=item_data['quantity'],
                price=item_data['price']
            )
            total_amount += item.price * item.quantity
        
        order.total_amount = total_amount
        order.save()
        return order
